using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Diagnostics;

namespace BizTalk.BuildGenerator.Tasks.Tests
{
    /// <remarks />
    [TestClass]
    public abstract class MSBuildTest
    {        
        /// <remarks />
        private static readonly string _msBuildPath = Environment.ExpandEnvironmentVariables(@"%systemdrive%\WINDOWS\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe");

        /// <remarks />
        protected static int RunMSBuild(string msbuildExeArguments)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(".");
            return RunMSBuild(msbuildExeArguments, directoryInfo.FullName);
        }

        /// <remarks />
        protected static int RunMSBuild(string msbuildExeArguments, string workingDirectory)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo(_msBuildPath, msbuildExeArguments);
            processStartInfo.CreateNoWindow = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.WorkingDirectory = workingDirectory;
            Process process = Process.Start(processStartInfo);
            Console.WriteLine(process.StandardOutput.ReadToEnd());
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                Console.WriteLine(process.StandardError.ReadToEnd());
            }
            return process.ExitCode;
        }

        /// <remarks />
        protected void GetFileAndWriteToPath(string fileResourceName, string filePathToBeWrittenTo)
        {
            Stream resourceStream = this.GetType().Assembly.GetManifestResourceStream(fileResourceName);
            using (StreamReader sr = new StreamReader(resourceStream))
            {
                using (StreamWriter sw = new StreamWriter(filePathToBeWrittenTo))
                {
                    while (sr.Peek() >= 0)
                    {
                        sw.WriteLine(sr.ReadLine());
                    }
                    sw.Flush();
                }
            }             
        }
    }
}

